//
//  ZZCUserAccountViewModel.swift
//  weibo
//
//  Created by zhangzuchao on 17/3/29.
//  Copyright © 2017年 zhangZuChao. All rights reserved.
//

import UIKit

class ZZCUserAccountViewModel: NSObject {
    //  单例的全局访问点
    static let sharedViewModel: ZZCUserAccountViewModel = ZZCUserAccountViewModel()
    
    //  重写init构造函数
    private override init() {
        super.init()
        
        //  获取本地归档的对象
        userAccount = ZZCUserAccount.loadUserAccount()
    }
    
    //  viewModel引用模型
    var userAccount: ZZCUserAccount?
    
    //  封装获取accessToken的逻辑
    var accessToken: String? {
        
        //  获取过期时间对象
        if userAccount?.expiresDate?.compare(Date()) == ComparisonResult.orderedDescending {
            
            //  如果是降序,说明没有过期
            return userAccount?.access_token
        }
        
        return nil
        
    }
    //  封装是否登录的操作
    var isLogin: Bool {
        return accessToken != nil
    }
    
 
    //  通过code获取accesstoken
    func requestAccessToken(code: String, callBack: @escaping (Bool)->()) {
        
        ZZCNetworkTools.shareTools.requestAccessToken(code: code) { (response, error) in
            if error != nil {
                print("网络请求异常: \(error!)")
                //  数据的回调
                callBack(false)
                return
            }
            
            guard let dic = response as? [String: Any] else {
                print("服务端数据格式不对")
                callBack(false)
                return
            }
            
            //  代码执行到此表示oc对象(字典或者数组)
            let userAccount = ZZCUserAccount(dic: dic)
            //  通过uid 和 accesstoken获取用户数据
            self.requesUserInfo(userAccount: userAccount, callBack: callBack)
        }
    }
    
    //  通过accessToken和uid获取用户新
    fileprivate func requesUserInfo(userAccount: ZZCUserAccount, callBack: @escaping (Bool)->()) {
        //  获取令牌
        let accessToken = userAccount.access_token!
        //  用户id
        let uid = userAccount.uid
        ZZCNetworkTools.shareTools.requestUserInfo(accessToken: accessToken, uid: uid) { (response, error) in
            if error != nil {
                print("网络请求异常: \(error!)")
                callBack(false)
                return
            }
            
            guard let dic = response as? [String: Any] else {
                print("服务端数据格式不对")
                callBack(false)
                return
            }
            
            //  代码执行到此字典一定有值
//            print(dic)
            
            //  给对象里面的name和头像赋值
            let name = dic["name"] as? String
            let avatar_large = dic["avatar_large"] as? String
            userAccount.name = name
            userAccount.avatar_large = avatar_large
            
            //  保存用户对象
            userAccount.saveUserAccount()
            //  给属性赋值
            self.userAccount = userAccount
            //  获取到用户信息并且归档完成表示登录成功
            callBack(true)
        }
    }
}











